<template>
  <div class="stepsWrap">
    <div class="content">
      <div class="headBox">
        <a-steps :current="current">
          <a-step>
            <!-- <span slot="title">Finished</span> -->
            <template slot="title"> 导出条件 </template>
            <span slot="description">请选择</span>
          </a-step>
          <!-- sub-title="Left 00:00:08" -->
          <a-step title="进行中" description="制单中" />
          <a-step title="下载中" description="文件下载中" />
          <a-step title="完成" description="下载完成" />
        </a-steps>
      </div>
      <div class="info" :dataType="otherProps.type || ''">
        <div class="contentForm">
          <template v-if="current == 0">
            <div class="typeChange">
              <a-radio-group :value="radioVal" button-style="solid" @change="radioChange" v-if="isShowWeek">
                <a-radio-button value="week"> 数据分析 </a-radio-button>
                <a-radio-button value="loop"> 未闭环 </a-radio-button>
              </a-radio-group>
              <a-radio-group :value="radioVal" button-style="solid" @change="radioChange" v-else>
                <a-radio-button value="month"> 月分析 </a-radio-button>
                <a-tooltip>
                  <template slot="title">
                    <span>开发中</span>
                  </template>
                  <a-radio-button value="quarter" :disabled="true"> 季度分析 </a-radio-button>
                </a-tooltip>
              </a-radio-group>
            </div>
            <div class="formItem">
              <a-row :gutter="[12, 24]">
                <a-col :span="24" v-if="radioVal == 'month'">
                  <a-col class="title" :span="4">日期</a-col>
                  <a-col :span="20">
                    <a-month-picker :value="tempDateForm" @change="dateChange" placeholder="请选择月份"
                      style="width: 100%" />
                  </a-col>
                </a-col>
                <a-col :span="24" v-else-if="radioVal == 'quarter'">
                  <a-col class="title" :span="4">季度</a-col>
                  <a-col :span="20">
                    <a-space>
                      <div style="width: 132px">
                        <FormYear :formData="formData" dataIndex="yearDate" :onCallBack="dateYearChange"></FormYear>
                      </div>
                      <a-select placeholder="请选择季度" style="width: 132px" :options="selectOptions"></a-select>
                    </a-space>
                  </a-col>
                </a-col>
                <a-col :span="24" v-else-if="['loop', 'week'].includes(radioVal)">
                  <a-col class="title" :span="4">时间</a-col>
                  <a-col :span="20">
                    <a-range-picker :value="formData['date']" @change="dateChange" style="width: 100%;" />
                  </a-col>
                </a-col>
                <a-col :span="24">
                  <a-col class="title" :span="4">公司</a-col>
                  <a-col :span="20">
                    <div class="plaTitke" v-if="false">
                      <template>
                        <span v-if="newTreeKey.label" style="color: #00000080">{{
                          newTreeKey.label
                        }}</span>
                        <span v-else>请选择左侧树状图</span>
                      </template>
                    </div>
                    <template v-else>
                      <FormTreeSelect :onCallBack="onChangeBack" :formData="formData" dataIndex="company"
                        :treeList="newTreeList"></FormTreeSelect>
                    </template>
                  </a-col>
                </a-col>
              </a-row>
            </div>
          </template>
          <template v-else-if="[1, 2].includes(current)">
            <a-result :title="`${current == 1 ? '制单' : '下载'}过程中，请稍等!`">
              <template #icon>
                <a-icon type="loading" theme="outlined" />
              </template>
            </a-result> </template><template v-else-if="[3].includes(current)">
            <a-result :title="`制单成功，请等待下载`">
              <template #icon>
                <a-icon type="smile" theme="twoTone" />
              </template>
              <template #extra> </template>
            </a-result>
          </template>
        </div>
      </div>
      <div class="endBox">
        <a-space>
          <a-button type="primary" @click="handNext" :disabled="isDisabled" :loading="loading">{{
            buttonTitle
          }}</a-button>
          <!-- <Preview :isDisabled="isDisabled" :formData="formData" :type="radioVal" :formType="formType"></Preview> -->
          <!-- <a-button v-if="current == 1">上一步</a-button> -->
        </a-space>
      </div>
    </div>
  </div>
</template>
<script>
import moment from "moment";
import FormYear from "./components/FormYear";
import FormTreeSelect from "./components/FormTreeSelect.vue";
import qs from "qs";
import Preview from '@/components/ZSButton/Preview';

export default {
  name: "Steps",
  components: {
    FormYear,
    FormTreeSelect,
    Preview,
  },
  props: {
    treeKey: {
      type: Object,
      default: () => { },
    },
    treeList: {
      type: [Object, Array],
      default: () => [],
    },
    otherProps: {
      type: Object,
      default: () => ({}),
    },
    formType: {
      type: String,
    }
  },
  data() {
    return {
      current: 0,
      radioVal: "month",
      formData: {
        date: null,
        yearDate: null,
        company: "",
      },
      loading: false,
      // 季度
      open: false,
      selectedQuarter: "",
      selectOptions: [
        { label: "第一季度", value: 1 },
        { label: "第二季度", value: 2 },
        { label: "第三季度", value: 3 },
        { label: "第四季度", value: 4 },
      ],
      newTreeList: [],
      newTreeKey: {
        label: '',
        value: ',,'
      },
    };
  },
  computed: {
    buttonTitle() {
      let cur = this.current;
      let str;
      if (cur == 3) {
        str = "重新导出";
      } else if (cur == 1) {
        str = "进行中";
      } else {
        str = "下一步";
      }
      return str;
    },
    isDisabled() {
      let cur = this.current;
      let isBoolean = false;
      if (cur == 0) {
        let tempForm = this.formData;
        if (['week', 'loop'].includes(this.radioVal)) {
          if (tempForm["company"] != "" && Array.isArray(this.formData.date) && this.formData.date.length > 0) {
            isBoolean = false;
          } else {
            isBoolean = true;
          }
        }
        // else if (this.radioVal == 'week') {
        //   if (tempForm["company"] != "") {
        //     isBoolean = false;
        //   } else {
        //     isBoolean = true;
        //   }
        // } 
        else {
          if (tempForm["date"] && tempForm["date"] != "" && tempForm["company"] != "") {
            isBoolean = false;
          } else {
            isBoolean = true;
          }
        }

      }
      return isBoolean;
    },
    tempDateForm() {
      return this.formData["date"] ? moment(this.formData["date"]) : null;
    },
    tempDateRange() {
      return this.formData["date"] ? [moment(this.formData["date"][0], 'YYYY-MM-DD'), moment(this.formData["date"][1], 'YYYY-MM-DD')] : null;
    },
    dateYearChange(e) {
      let tempData = this.formData;
      tempData["yearDate"] = e;
      this.formData = tempData;
    },
    // 判断是不是传进来的数据，就是是不是 从【应用商店过来的】
    isShowWeek() {
      let isBoolean = false;
      if (Object.keys(this.otherProps).length > 0 && this.otherProps.type != '') {
        isBoolean = true;
      }
      return isBoolean;
    }
  },
  methods: {
    radioChange(e) {
      this.radioVal = e.target.value;
      // 切换类型是不是要清楚表单的数据 清楚上次选择的内容
      if (true) {
        let tempForm = this.formData;
        this.formData = {
          ...tempForm,
          date: null,
          yearDate: null,
          company: "",
        }
      }
    },
    handNext() {
      let cur = this.current;
      if (cur == 0) {
        this.getFilesData();
        return;
      } else if (cur == 3) {
        cur = 0;
      } else {
        cur = cur + 1;
      }
      this.current = cur;
    },
    dateChange(e, s) {
      this.formData = {
        ...this.formData,
        date: s,
      };
    },
    getFilesData() {
      let params = {
        type: this.radioVal,
      };
      let questUrl;
      if (params.type == 'week') {
        questUrl = this.$excelExportWeek;
      } else if (params.type == 'loop') {
        questUrl = this.$excelClosedLoopExport;
      } else {
        questUrl = this.$getexportzlfxmonth;
      }
      if (this.formType == 'modal') {
        questUrl = this.$monthlyStatement
      }
      let formData = this.formData;
      let cur = this.current;
      if (cur == 0) {
        if (params.type == 'week') {
          params["company"] = formData["company"];
          params["startTime"] = formData["date"][0];
          params["endTime"] = formData["date"][1];
        } else if (params.type == 'loop') {
          params["company"] = formData["company"];
          params["startTime"] = formData["date"][0];
          params["endTime"] = formData["date"][1];
        } else {
          params["code"] = formData["company"];
          params["date"] = formData["date"];
        }
      }
      this.loading = true;
      this.current = 1;
      let str = qs.stringify(params);
      this.current = 2;
      const link = document.createElement("a");
      link.style.display = "none";
      // 兼容不同浏览器的URL对象
      const url = window.URL || window.webkitURL || window.moxURL;
      link.href = `${questUrl}?${str}`;
      link.setAttribute("download", `${this.newTreeKey.label}${params.date}流程质量分析报告.docx`);
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      url.revokeObjectURL(link.href);
      this.current = 3;

      this.loading = false;
      // } else {
      return;
      this.getAxios(this.$getexportzlfxmonth, params)
        .then((res) => {
          if (res) {
            cur = cur + 1;
            this.current = cur;
            const blob = new Blob([res], {
              type: "application/vnd.openxmlformats-officedocument.wordprocessingml.document;charset=utf-8",
            }); // 构造一个blob对象来处理数据，并设置文件类型
            const link = document.createElement("a");
            link.style.display = "none";
            // 兼容不同浏览器的URL对象
            const url = window.URL || window.webkitURL || window.moxURL;
            link.href = url.createObjectURL(blob);
            link.setAttribute(
              "download",
              `${this.newTreeKey.label}${params.date}流程质量分析报告.docx`
            );
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            url.revokeObjectURL(link.href);
          }
        })
        .finally(() => {
          if (cur == 2) {
            cur = cur + 1;
            this.current = cur;
          }
          this.loading = false;
        });
      // }
    },
    // 季度
    handleOpenChange(status) {
      this.open = status;
      if (status) {
        const now = new Date();
        this.setSelectedQuarter(now);
      }
    },
    handleChange(date) {
      if (date && date instanceof Date) {
        this.setSelectedQuarter(date);
      }
    },
    setSelectedQuarter(date) {
      const month = date.getMonth();
      const quarter = Math.floor(month / 3) + 1;
      this.selectedQuarter = `${date.getFullYear()}年第${quarter}季度`;
    },
    onChangeBack(v, d) {
      let tempFormData = this.formData;
      tempFormData[d] = v;
      this.formData = tempFormData;
    },
    getNewTreeListData(aParams) {
      let params = {
        ...aParams,
      };
      this.getAxios(this.$hiddenMonthlyStatement, params).then((res) => {
        if (res.code == 200) {
          console.log('res===', res.data);
          this.newTreeList = res.data.treeList;
          this.newTreeKey = {
            ...this.newTreeKey,
            label: res.data.checkedDept.name,
            value: res.data.checkedDept.id,
          }
        }
      }).catch(() => {
      }).finally(() => {
      })
    }
  },
  mounted() {
    if (Object.keys(this.otherProps).length > 0 && this.otherProps.type != '') {
      this.radioVal = this.otherProps.type;
    }
  },
  watch: {
    treeKey: {
      handler(nVal, oVal) {
        if (this.formType == 'modal') {
        } else {
          this.newTreeKey = nVal;
        }
      },
      deep: true,
      immediate: true,
    },
    treeList: {
      handler(nVal, oVal) {
        if (this.formType == 'modal') {
          this.getNewTreeListData({
            deptId: this.treeKey.value,
          });
        } else {
          this.newTreeList = nVal;
        }
      },
      deep: true,
      immediate: true,
    },
    newTreeKey: {
      handler(nVal, oVal) {
        let tempForm = this.formData;
        tempForm["company"] = nVal.value || "";
        this.formData = tempForm;
      },
      deep: true,
      immediate: true,
    }
  },
};
</script>
<style lang="less" scoped>
.stepsWrap {
  width: 100%;
  height: 100%;
  background-color: #ffffff;

  .content {
    padding: 10px 10px 0px 10px;
    width: 100%;
    height: 100%;

    .headBox {
      height: 20vh;
      display: flex;
      align-items: center;
    }

    .info {
      height: calc(80vh - 61px - 20px - 10px - 40px);

      .contentForm {
        .typeChange {
          text-align: center;
        }

        .formItem {
          width: 400px;
          margin: 0 auto;
          //   background-color: orange;
          margin-top: 24px;

          .title {
            font-size: 16px;
            font-weight: 700;
            height: 56px;
            line-height: 32px;
          }

          .plaTitke {
            height: 32px;
            display: flex;
            align-items: center;
            padding: 12px 6px;
            color: #cdcdcd;
            // cursor: ;
            border: 1px solid #cdcdcd;
            border-radius: 4px;
            // pointer-events: none;
            cursor: not-allowed;
          }
        }
      }
    }

    .info[dataType='week'] {
      height: calc(80vh - 61px - 20px - 10px - 40px - 30px);
    }

    .endBox {
      width: 100%;
      height: 40px;
      display: flex;
      justify-content: center;
      align-items: center;
    }
  }
}
</style>
